package com.hj.system.system.filter;

import com.alibaba.fastjson.JSONObject;
import com.hj.system.base.utils.HttpServletUtils;
import com.hj.system.base.utils.ResponseUtil;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Shiro内置过滤器 anon         org.apache.shiro.web.filter.authc.AnonymousFilter
 * authc        org.apache.shiro.web.filter.authc.FormAuthenticationFilter
 * authcBasic   org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter
 * perms        org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter
 * port         org.apache.shiro.web.filter.authz.PortFilter
 * rest         org.apache.shiro.web.filter.authz.HttpMethodPermissionFilter
 * roles        org.apache.shiro.web.filter.authz.RolesAuthorizationFilter
 * ssl          org.apache.shiro.web.filter.authz.SslFilter
 * user         org.apache.shiro.web.filter.authc.UserFilter
 */
public class ShiroSessionFilter extends FormAuthenticationFilter {
    /**
     * 在访问controller前判断是否登录，返回json，不进行重定向。
     *
     * @param request
     * @param response
     * @return true-继续往下执行，false-该filter过滤器已经处理，不继续执行其他过滤器
     * @throws Exception
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        HttpServletRequest req = (HttpServletRequest) request;
        if (HttpServletUtils.jsAjax(req)) {
            httpServletResponse.setCharacterEncoding("UTF-8");
            httpServletResponse.setContentType("application/json");
            ResponseUtil responseUtil = ResponseUtil.error(403, "登录认证失效，请重新登录!", "/login");
            httpServletResponse.getWriter().write(JSONObject.toJSON(responseUtil).toString());
        } else {
            /**
             * @Mark 非ajax请求重定向为登录页面
             */
            httpServletResponse.sendRedirect("/login");
        }
        return false;
    }
}
